import React, { useState, useRef, useEffect } from 'react'
import { Form, Row, Col, Input, Empty, message, Spin } from 'antd';
import { useMeasure, useMount } from 'react-use';
import { withRouter } from 'umi';
import classNames from 'classnames';
import keyBy from 'lodash/keyBy';

import If from '@/components/If';
import DateFormatter from '@/components/DateFormatter';
import { processService } from '@/services/salaryManage/process';
import { isSuccess } from '@/utils/request';

import AutoRenderComponent
    from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';

import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName'
import MonthSalaryTemplate from './components/MonthSalaryTemplate';
import Context, { contextValue } from './context';
import OrganizationNameItem from './OrganizationNameItem';
import style from './index.less';

// 是否为申请状态
const isProcessApply = year => !!year;

const getWidthMapper = width => {
    let widthMapper;

    // 一列最小408计算
    if (width < 810) {
        widthMapper = {
            small: 24,
            large: 24
        };
    } else if (width < 1215) {
        widthMapper = {
            small: 12,
            large: 12
        };
    } else {
        widthMapper = {
            small: 12,
            large: 12
        };
    }

    return widthMapper;
};

const labelProp = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 }
};

const SalaryTemplateApply = (({ form, formValueMap, dataSource, location }) => {
    const [loading, setLoading] = useState(false);
    const [ref, { width }] = useMeasure();
    const widthMapper = getWidthMapper(width);

    const [pageModel, setPageModel] = useState(formValueMap?.salaryTemplateApplyModel || {});

    console.groupCollapsed('%cSalaryTemplateApply套件信息', 'color: #7e2065');
    console.log('formValueMap:', formValueMap);
    console.log('dataSource:', dataSource);
    console.log('location:', location);
    console.groupEnd();

    const childConfig = dataSource?.children?.length > 0 ? dataSource.children : [];
    const childrenConfigMap = keyBy(childConfig, 'formId');
    const summaryConfig = childrenConfigMap.summary;
    const organizationNameConfig = childrenConfigMap.organizationName;
    const uploadConfig = childrenConfigMap.OssUploadFiles;

    const { getFieldDecorator } = form;
    const before = pageModel.before || {};
    const after = pageModel.after || {};
    const leftList = Object.values(before) || [];
    const rightList = Object.values(after) || [];
    const leftRef = useRef();
    const rightRef = useRef();

    contextValue.leftList = leftList;
    contextValue.rightList = rightList;
    const [contextState, setContextState] = useState(contextValue);
    const context = { contextState, setContextState };

    const inputOnchange = event => setPageModel({ ...pageModel, remark: event.target.value });

    const year = location.query?.year;
    const organizationCode = location.query?.organizationCode;
    const isApply = isProcessApply(year);
    // 由于在申请界面或审批详情界面限定了90%的宽度(表单设计页没有限定)，而且我们要100%，所在增加了负值的marginRight
    const extraRight = isApply || formValueMap;

    // 如果流程附件配置为只读时，后台不会返回配置信息，就无需显示
    if (uploadConfig) {
        uploadConfig.uploadProps.disabled = uploadConfig.options.disabled;
    }

    useMount(() => {
        const scrollFn = () => {
            if (leftRef.current.scrollTop !== rightRef.current.scrollTop) {
                rightRef.current.scrollTop = leftRef.current.scrollTop;
            }
        };
        leftRef.current.addEventListener('scroll', scrollFn);

        return () => {
            leftRef.current.removeEventListener('scroll', scrollFn);
        };
    });

    useMount(async () => {
        // 如果是发起申请的界面
        if (isApply) {
            setLoading(true);
            try {
                const response = await processService.queryTemplateProcessModel(organizationCode, year);
                setLoading(false);
                if (isSuccess(response)) {
                    setPageModel(response.data);
                } else {
                    message.error(response.msg);
                }
            } catch (e) {
                setLoading(false)
            }
        }
    });

    useEffect(
        () => {
            if (formValueMap?.salaryTemplateApplyModel) {
                setPageModel(formValueMap?.salaryTemplateApplyModel);
            }
        },
        [formValueMap]
    );


    return (
        <Spin spinning={loading}>
            <div className={classNames(style.salaryTemplateProcess, { [style.extraRight]: extraRight })}>
                {
                    getFieldDecorator('salaryTemplateApplyModel', {
                        initialValue: pageModel
                    })(<Input type="hidden"/>)
                }

                {/* 行政机构 */}
                <OrganizationNameItem
                    form={form}
                    formValueMap={formValueMap}
                    organizationNameConfig={organizationNameConfig}
                    organizationCode={pageModel?.organizationCode}
                />

                {/* 流程名称 */}
                {
                    summaryConfig
                        ? <Form.Item
                            label={summaryConfig.label}
                            key={summaryConfig.formId}
                            style={{ display: summaryConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(summaryConfig?.formId, {
                                rules: summaryConfig?.rules,
                                initialValue: formValueMap?.[summaryConfig.formId]
                                    ?? summaryConfig?.options?.initialValue
                            })(<AutoRenderComponent form={form} config={summaryConfig} />)}
                        </Form.Item>
                        : null
                }

                <div ref={ref} style={{ maxWidth: 900 }} className={style.ml8}>
                    <If condition={pageModel?.organizationCode || formValueMap?.applicationNo }>
                        <Row>
                            <If condition={pageModel?.organizationCode}>
                                <Col span={widthMapper.small}>
                                    <Form.Item label="行政机构：" className={classNames(style.mb0)} {...labelProp}>
                                        <OrganizationNameConnect organizationCode={pageModel.organizationCode} />
                                    </Form.Item>
                                </Col>
                            </If>

                            <If condition={formValueMap?.applicationNo}>
                                <Col span={widthMapper.small}>
                                    <Form.Item label="申请编号：" className={classNames(style.mb0)} {...labelProp}>
                                        {formValueMap?.applicationNo}
                                    </Form.Item>
                                </Col>
                            </If>
                        </Row>
                    </If>

                    <Row>
                        <Col span={widthMapper.small}>
                            <Form.Item label="申请人员：" className={classNames(style.mb0)} {...labelProp}>
                                {pageModel.approver}
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.small}>
                            <Form.Item label="所在部门：" className={classNames(style.mb0)} {...labelProp}>
                                {pageModel.dept}
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.small}>
                            <Form.Item label="申请日期：" className={classNames(style.mb0)} {...labelProp}>
                                <DateFormatter value={pageModel.approveStartTime} pattern="YYYY-MM-DD" />
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.small}>
                            <Form.Item label="月模板年份：" className={classNames(style.mb0)} {...labelProp}>
                                {pageModel.year ? `${pageModel.year}年` : ''}
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.large}>
                            <Form.Item label="重要提示：" className={classNames(style.mb0)} {...labelProp}>
                                {!isApply
                                    ? <span className={style.info} ><EmptyPlaceHolder value={pageModel.remark} /></span>
                                    : <Input
                                        maxLength={200}
                                        onChange={inputOnchange}
                                        disabled={!isApply}
                                        value={pageModel.remark}
                                    />}
                            </Form.Item>
                        </Col>
                    </Row>
                </div>
                <Context.Provider value={context}>
                    <Row type="flex" gutter={16} className="compare">
                        <Col className="compare-item">
                            <h6 className="compare-item-title">变更前</h6>
                            <div ref={leftRef} className="compare-item-body">
                                <If condition={leftList?.length > 0}>
                                    {leftList.map(data => (
                                        <MonthSalaryTemplate
                                            key={data.month}
                                            data={data}
                                            prefix="left"
                                            showChange={false}
                                        />
                                    ))}
                                </If>
                                <If condition={!leftList?.length}>
                                    <Empty
                                        description="暂无数据"
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        style={{ marginLeft: '20px' }}
                                    />
                                </If>
                            </div>
                        </Col>
                        <Col className="compare-item">
                            <h6 className="compare-item-title">变更后</h6>
                            <div ref={rightRef} className="compare-item-body">
                                <If condition={rightList?.length > 0}>
                                    {rightList.map(data => (
                                        <MonthSalaryTemplate
                                            key={data.month}
                                            data={data}
                                            compareData={before[data.month]}
                                            prefix="right"
                                            showChange
                                        />
                                    ))}
                                </If>
                                <If condition={!rightList?.length}>
                                    <Empty
                                        description="暂无数据"
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        style={{ marginLeft: '20px' }}
                                    />
                                </If>
                            </div>
                        </Col>
                    </Row>
                </Context.Provider>
                {
                    uploadConfig
                        ? <Row>
                            <Form.Item label="附件：" className={classNames(style.mb0, style.flex)}>
                                {getFieldDecorator(uploadConfig?.formId, {
                                    rules: uploadConfig?.rules,
                                    initialValue: formValueMap?.[uploadConfig.formId] ?? uploadConfig.initialValue
                                })(<AutoRenderComponent form={form} config={uploadConfig} />)}
                            </Form.Item>
                        </Row>
                        : null
                }
            </div>
        </Spin>
    );
});

export default withRouter(React.memo(SalaryTemplateApply));
